<?
/**
 * VoiceOne Settings/Extensions/edit
 *
 * Frontend to provide access to the extensions system in voiceone.
 * @package voiceone
 * @subpackage  settings_extensions
 * @todo Remove hardcoded italian message for confirmation box (AlertGood. AlertBad etc)
 */
 
  include ("../../../../admin/config/cfg.php");
  global $cwlang;
  require_once("$absBasePath/lib/xajax/xajax.inc.php"); 
  sajax_init();
  
  //================ XAJAX ================
	function delCidRow($trunk_id){
    global $asterisk,$cwlang;
		// Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
		// Build response
		$ret=$asterisk->getTrunk($trunk_id,0);
  	if (is_array($ret)){
			$t=$ret[0];
      $trunk_name=$t["name"];
		}
    $script.=" document.getElementById('stats').deleteRow(document.getElementById('".$trunk_id."_row').rowIndex); ";
		$script.=" var optObj=document.createElement('option'); ";
		$script.=" optObj.value='".$trunk_id."'; ";
		$script.=" optObj.innerText='".$trunk_name."'; ";   //cross browser fix 
    $script.=" optObj.text='".$trunk_name."'; ";        //cross browser fix
    $script.=" document.getElementById('trunklist').appendChild(optObj); ";
    $script.=" if(document.getElementById('stats').rows.length==1){ ";
    $script.="   var newRow = document.getElementById('stats').insertRow(document.getElementById('stats').rows.length); ";
    $script.="   newRow.id = 'tableintro'; ";
    $script.="   newRow.bgColor = '#ffffff'; ";
    $script.="   var newCell_01 = newRow.insertCell(0); newCell_01.colSpan = '3'; newCell_01.innerHTML = '&nbsp;'; ";
    $script.="   var newCell_234 = newRow.insertCell(1); newCell_234.colSpan = '3'; newCell_234.innerHTML = '".T_('Caller ID is set to default for all lines')."'; ";
    $script.="} ";
    // Return the xajaxResponse object
		$objResponse->addScript($script);
    return $objResponse->getXML(); 
  }
  function addCid($trunk_id){
    global $asterisk,$relBasePath;
		// Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
		// Build response
  	$ret=$asterisk->getTrunk($trunk_id,0);
  	if (is_array($ret)){
			$t=$ret[0];
      $trunk_name=$t["name"];
    	$trunk_cidnum=$t["cid_number"];
  		$trunk_cidname=$t["cid_name"];
  		$trunk_force=$t["force_cid"];
  		$truk_clir=$t["clir"];
  		$truk_numbers=$t["cid_list"];
  		if (is_array($truk_numbers)) 
  	  foreach ($truk_numbers as $number) $trunk_cidlist.="<option value=\"$number\">$number</option>";
		}
    if($trunk_force==1) $forceChecked="checked=\"checked\""; else $forceChecked="";
		$cell0="<img src=\"".$relBasePath."public/img/trash.gif"."\" alt=\"delTrunk\" onclick=\"xajax_delCidRow('".$trunk_id."')\" />";
		$cell1="<input type=\"checkbox\" id=\"cid[".$trunk_id."][clir]\" name=\"cid[".$trunk_id."][clir]\" />";
		$cell2="$trunk_name<input type=\"hidden\" id=\"cid[".$trunk_id."][id]\" name=\"cid[".$trunk_id."][id]\" value=\"".$trunk_id."\" /><input type=\"hidden\" id=\"cid[".$trunk_id."][name]\" name=\"cid[".$trunk_id."][name]\" value=\"".$trunk_name."\" />";
		$cell3="<select id=\"cid[".$trunk_id."][cidnum]\" name=\"cid[".$trunk_id."][cidnum]\" >".$trunk_cidlist."</select>";
		$cell4="<input type=\"text\" id=\"cid[".$trunk_id."][cidname]\" name=\"cid[".$trunk_id."][cidname]\" value=\"".$trunk_cidname."\" />";
    //$cell5="<input type=\"checkbox\" id=\"cid[".$trunk_id."][force]\" name=\"cid[".$trunk_id."][force]\" $forceChecked disabled=\"disabled\" />";
    if($forceChecked!="") $cell5="<span style=\"color: red;\"><strong>ON<strong></span>"; else $cell5="<span style=\"color: black;\">".T_('OFF')."</span>";
    // Return the xajaxResponse object
		$objResponse->addAssign($trunk_id."_row_cell0","innerHTML",$cell0);
    $objResponse->addAssign($trunk_id."_row_cell1","innerHTML",$cell1);
    $objResponse->addAssign($trunk_id."_row_cell2","innerHTML",$cell2);
    $objResponse->addAssign($trunk_id."_row_cell3","innerHTML",$cell3);
		$objResponse->addAssign($trunk_id."_row_cell4","innerHTML",$cell4);
    $objResponse->addAssign($trunk_id."_row_cell5","innerHTML",$cell5);
    $objResponse->addScript(" document.getElementById('trunklist').remove(document.getElementById('trunklist').selectedIndex); ");
    $objResponse->addScript(" document.getElementById('stats').deleteRow(document.getElementById('tableintro').rowIndex); "); 
    return $objResponse->getXML(); 
  }
	function roll(){
    global $relBasePath,$cwlang;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    // Build response
    $html=" <img src=\"".$relBasePath."public/img/ico-progress.gif"."\" alt=\"loading\" /><span>".T_('loading')."</span>";
    $objResponse->addAssign("loading","innerHTML",$html);
    // Return the xajaxResponse object
    return $objResponse->getXML(); 
  }
  function processFormData($formData){
    global $asterisk,$cwlang,$relBasePath;
    // Instantiate the xajaxResponse object
    $objResponse = new xajaxResponse();
    $confirmBeforeSubmit="";
    //extract form params
    $virtual=$formData["virtual"];
    $id=$virtual["id"];
    $exten=$virtual["extension"];
    $password=$virtual["password"];
    $confirm=$virtual["confirm"];
    $voicemailOn=$virtual["voicemailOn"];
    $vid=$virtual["vid"];
    $vpassword=$virtual["vpassword"];
    $vconfirm=$virtual["vconfirm"];
    $linked_clients=$formData["listRight"];
		if(isset($formData["cid"])) $cidArr=$formData["cid"];
    $imgErr="<img src=\"".$relBasePath."/public/img/shutdown.png\" alt=\"error\">";
    //retrieve old exten and alias value
    if($id!=""){
      $ret=$asterisk->getVirtualExtension($id);
      $v=$ret[0];
      $oldExen=$v["extension"];
    }
    // Check Extension ((no null)&&(numeric)&&(unique)&&( -neq Alias)
    $extensionErr=false;
    if($exten=="") { 
      //extension cannot be null
      $errOut[]= T_('User extension cannot be null');
      $objResponse->addAssign("extensionErr","innerHTML",$imgErr);
      $extensionErr=true;
    }else{
      //extension must be numeric
      for($i=0; $i<strlen($exten); $i++){
        $ch=ord($exten[$i]);
        if(!((($ch>47)&&($ch<58)))){
          $errOut[]= T_('User extension allow only numeric characters. Please change it');
          $objResponse->addAssign("extensionErr","innerHTML",$imgErr);
          $extensionErr=true;
          break;
        }
      }
      //extension must be unique
      if(!(($id!="")and($exten==$oldExen))) {
        $ret=$asterisk->getExtension(0);
        if(is_array($ret)){
          foreach($ret as $e) {
            if($exten==$e["extension"]){
              $errOut[]= T_('User extension already exists. Please change it');
              $objResponse->addAssign("extensionErr","innerHTML",$imgErr);
              $extensionErr=true;
            }
          }
        }
      }
    }
    if($extensionErr===false) $objResponse->addAssign("extensionErr","innerHTML","");
    // Check Account Password ((no null)&&(==confirm)&&(alphanumeric))
    $passwordErr=false;
    if($password==""){
      //account password cannot be not null
      $errOut[]=T_('Account password cannot be null');
      $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
      $passwordErr=true;
    }else if($password!=$confirm){
      //account password must be equal to confirm
      $errOut[]=T_('Account password and confirmation password do not match');
      $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
      $objResponse->addAssign("confirmErr","innerHTML",$imgErr);
      $passwordErr=true;
    }else{
      //account password must be alphanumeric
      for($i=0; $i<strlen($password); $i++){ 
        $ch=ord($password[$i]);
        if(!((($ch>96)&&($ch<123))||(($ch>64)&&($ch<91))||(($ch>47)&&($ch<58)))){
          $errOut[]=T_('Account password allows only alphanumeric characters. Please change it');
          $objResponse->addAssign("passwordErr","innerHTML",$imgErr);
          $passwordErr=true;
          break;
        }
      }
    }
    if($passwordErr===false){
      $objResponse->addAssign("passwordErr","innerHTML","");
      $objResponse->addAssign("confirmErr","innerHTML","");
    }
    // Check Linked Clinets (not null)
    $linked_clientsErr=false;
    if((!is_array($linked_clients))||(count($linked_clients)==0)){
    	//client list must be not emplty
      $errOut[]=T_('The list of clients linked to this extension can not be empty');
      $objResponse->addAssign("linked_clientsErr","innerHTML",$imgErr);
      $linked_clientsErr=true;
    }
    if($linked_clientsErr===false) $objResponse->addAssign("linked_clientsErr","innerHTML","");
    // Check Voicemail Password ((==confirm)&&(numeric))
    if ($voicemailOn=="1") {
      $vpasswordErr=false;
      if($vpassword!=$vconfirm){
        //voicemail password must be equal to confirm
        $errOut[]=T_('Voicemail password and confirmation password do not match');
        $objResponse->addAssign("vpasswordErr","innerHTML",$imgErr);
        $objResponse->addAssign("vconfirmErr","innerHTML",$imgErr);
        $vpasswordErr=true;
      }else{
        //voicemail password must be numeric
        for($i=0; $i<strlen($vpassword); $i++){ 
          $ch=ord($vpassword[$i]);
          if(!((($ch>47)&&($ch<58)))){
            $errOut[]=T_('Voicemail password allows only numeric characters. Please change it');
            $objResponse->addAssign("vpasswordErr","innerHTML",$imgErr);
            $vpasswordErr=true;
            break;
          }
        }
      }
    }else{
      //mailbox already exists?
      if($extensionErr!==true){
      	$ret=$asterisk->getVoiceMail($exten);
      	if((is_array($ret))&&(is_array($ret[0]))&&($ret[0]["id"]!=$vid)){
        	$confirmBeforeSubmit=T_('A mailbox is alredy defined for this extension.\\nIf you continue they will be linked together.\\nAre you sure?');
      	}
      }
    }
    if($vpasswordErr===false){
      $objResponse->addAssign("vpasswordErr","innerHTML","");
      $objResponse->addAssign("vconfirmErr","innerHTML","");
    }
    // Process Form
    if(isset($errOut)){
      $error="<div class=\"AlertBad\"><ul>";
      foreach($errOut as $err) $error.="<li>".$err."</li>";
      $error.="</ul></div>";
      $objResponse->addAssign("alert","innerHTML",$error);
      $objResponse->addAssign("loading","innerHTML","");
    }else{
      $objResponse->addAssign("loading","innerHTML","");
      if($confirmBeforeSubmit!="") $script=" if(confirm('".$confirmBeforeSubmit."')) document.getElementById('mainform').submit(); "; 
      else $script=" document.getElementById('mainform').submit(); ";
      $objResponse->addScript($script);
    }
    // Return the xajaxResponse object
    return $objResponse->getXML();  
  }
  $xajax = new xajax();
	$xajax->registerFunction("addCid");
	$xajax->registerFunction("delCidRow");
  $xajax->registerFunction("roll");
  $xajax->registerFunction("processFormData");
  $xajax->processRequests();
  //================== POST ====================
  
  if(count($_POST)>0){
  	//set general info 
    $entry=Array(
          "id" => $virtual["id"],
          "name" => $virtual["name"],
          "surname" => $virtual["surname"],
          "extension" => $virtual["extension"],
          "rule" => $virtual["rule"],
        //"username" => $virtual["username"],
          "password" => $virtual["password"],
          "language" => $virtual["language"],
          "linked_clients" => $_POST["listRight"],
          "groups" => $_POST["group"]
        );
    //set voicemail
    if($virtual["voicemailOn"]=="1") {
      $mailbox["mailbox"]=$virtual["extension"];
      $mailbox["password"]=$virtual["vpassword"];
      $mailbox["fullname"]=$virtual["name"]." ".$virtual["surname"];
      $mailbox["email"]=$virtual["email"];
      $mailbox["attach"]=$virtual["attach"];
      $mailbox["saycid"]=$virtual["saycid"];
      $mailbox["hidefromdir"]=$virtual["hidefromdir"];
      $entry["voicemail"]=$mailbox;
    }else{
      //if mailbox already exists link extension to mailbox
      /*
      $ret=$asterisk->getVoiceMail($client["extension"]);
      if((is_array($ret))&&(is_array($ret[0]))&&($ret[0]["id"]!=$virtual["vid"])){
        $mailbox["mailbox"]=$virtual["extension"];
        $mailbox["password"]=$ret[0]["password"];
        $mailbox["fullname"]=$virtual["name"]." ".$virtual["surname"];
        $mailbox["email"]=$ret[0]["email"];
        $mailbox["attach"]=$ret[0]["attach"];
        $mailbox["saycid"]=$ret[0]["saycid"];
        $mailbox["hidefromdir"]=$ret[0]["hidefromdir"];
        $entry["voicemail"]=$mailbox;
      }
      */
    }
    //set Cid
    $cidArr=array();
    if(is_array($_POST["cid"])){
    	foreach($_POST["cid"] as $t){
    	  $cid=array(
        		"id" => 0,
            "trunk" => $t["id"],
            "cid_number" => $t["cidnum"],
    		  	"cid_name" =>$t["cidname"]
          );
    		if(isset($t["clir"])&&($t["clir"]=="on")) $cid["clir"]=1;
				else $cid["clir"]=0;
    		$cidArr[]=$cid;
    	}
    }
    $entry["cid"]=$cidArr;
    //put Client 
    $ret=$asterisk->putVirtualExtension($entry);
    if($ret>0){
      $alert="<div class=\"AlertGood\">".T_('Virtual Extension successfully saved')."</div>";
      $_GET["id"]=$ret;
    }else{
		  $alert="<div class=\"AlertBad\">".T_('Edit failed')."</div>";
	  }
	  //go to main page
    goToMainPage($alert,"../");
  }
    
  //================ PAGE LOGIC ================
  //Get the client informations
  if (isset($_GET["id"]) and $_GET["id"]!="") {
    $id=$_GET["id"];
    $ret=$asterisk->getVirtualExtension($id);
    if($err=$asterisk->getError()) die("Error: $err");
    $v=$ret[0];
    $id=$v["id"];
    $name=$v["name"];
    $surname=$v["surname"];
    $extension=$v["extension"];
    $username=$v["username"];
    $password=$v["password"];
    $language=$v["language"];
    $rule=$v["rule"];
    $linked_clients=$v["linked_clients"];
    $groupsArr=$v["groups"];
    $voicemailArr=$v["voicemail"];
    $cidArr=$v["cid"];
    $id_application=$v["id_application"];
    //read the mailbox
    if((is_array($voicemailArr))&&(count($voicemailArr)>0)){
      $voicemailOn="1"; 
      $vid=$voicemailArr["id"];
      $vpassword=$voicemailArr["password"];
      $email=$voicemailArr["email"];
      $attach=$voicemailArr["attach"];
      $saycid=$voicemailArr["saycid"];
      $hidefromdir=$voicemailArr["hidefromdir"];
    }else $voicemailOn="0";
		//load cid
  	if(is_array($cidArr)){
      foreach($cidArr as $c){
        $trunk_id=$c["trunk"];
  			$clir=$c["clir"];
  			$cidnum=$c["cid_number"];
  			$cidname=$c["cid_name"];
        error_log("Trunk: ".$trunk_id);
  			$trunkArr=$asterisk->getTrunk($trunk_id,0);
        if(is_array($trunkArr)){
          $t=$trunkArr[0];
          $trunk_name=$t["name"];
      		$truk_numbers=$t["cid_list"];
          $trunk_force=$t["force_cid"];
          $numberslist="";
      		if (is_array($truk_numbers)) 
      	  foreach ($truk_numbers as $number){
            if($cidnum==$number) $numberslist.="<option value=\"$number\" selected=\"selected\">$number</option>";
            else $numberslist.="<option value=\"$number\">$number</option>";
          }
    		}
        if($trunk_force==1) $forceChecked="checked=\"checked\""; else $forceChecked="";
        if($clir==1) $checked="checked=\"checked\""; else $checked="";
    		$cidlist.="<tr id=\"".$trunk_id."_row\" bgcolor=\"#ffffff\">";
      	$cidlist.="<td><img src=\"".$relBasePath."public/img/trash.gif"."\" alt=\"delTrunk\" onclick=\"xajax_delCidRow('".$trunk_id."')\" /></td>";
      	$cidlist.="<td><input type=\"checkbox\" id=\"cid[".$trunk_id."][clir]\" name=\"cid[".$trunk_id."][clir]\" $checked /></td>";
      	$cidlist.="<td>$trunk_name<input type=\"hidden\" id=\"cid[".$trunk_id."][id]\" name=\"cid[".$trunk_id."][id]\" value=\"".$trunk_id."\" /><input type=\"hidden\" id=\"cid[".$trunk_id."][name]\" name=\"cid[".$trunk_id."][name]\" value=\"".$cidname."\" /></td>";
        $cidlist.="<td><select id=\"cid[".$trunk_id."][cidnum]\" name=\"cid[".$trunk_id."][cidnum]\">".$numberslist."</select></td>";
      	$cidlist.="<td><input type=\"text\" id=\"cid[".$trunk_id."][cidname]\" name=\"cid[".$trunk_id."][cidname]\" value=\"".$cidname."\"/></td>";
        if($forceChecked!="") $cidlist.="<td><span style=\"color: red;\"><strong>ON<strong></span></td>"; else $cidlist.="<td><span style=\"color: black;\">".T_('OFF')."</span></td>";
      	$cidlist.="</tr>\n";
  			$trunksOnCid[]=$trunk_id;
      }
    }
    if(!(is_array($trunksOnCid))) $cidlist="<tr id=\"tableintro\" bgcolor=\"#ffffff\"><td colspan=\"3\"></td><td colspan=\"3\">".T_('Caller ID is set to default for all lines')."</td></tr>";
		//create trunk list
  	$ret=$asterisk->getTrunk(0,0);
  	if(is_array($ret)){
      foreach($ret as $t){
        $trunk_id=$t["id"];
        $trunk_name=$t["name"];
        $trunk_enable=$t["enable_cid"];
        if($trunk_enable==1){
    			if(is_array($trunksOnCid)){
            if (!(in_array($trunk_id,$trunksOnCid))) $trunklist.="<option id=\"".$trunk_id."_opt\" value=\"$trunk_id\">$trunk_name</option>";
          } 
          else $trunklist.="<option id=\"".$trunk_id."_opt\" value=\"$trunk_id\">$trunk_name</option>";
        }
  		}
    }
    //title
    $title=sprintf(__("Account: %1\$s &lt;%2\$s %3\$s&gt;"),$extension ,$surname, $name );
  }
  else{
	  //load cid
	  $cidlist="<tr id=\"tableintro\" bgcolor=\"#ffffff\"><td colspan=\"3\"></td><td colspan=\"3\">".T_('Caller ID is set to default for all lines')."</td></tr>";
	  //create trunk list
  	$ret=$asterisk->getTrunk(0,0);
  	if (is_array($ret))
    foreach ($ret as $t) {
      $trunk_id=$t["id"];
      $trunk_name=$t["name"];
      $trunk_enable=$t["enable_cid"];
      if($trunk_enable==1) $trunklist.="<option id=\"".$trunk_id."_opt\" value=\"$trunk_id\">$trunk_name</option>";
    }
    //title
    $title=T_('New Virtual Extension');
    unset($v);
  }
  //create the language list
  $langSelect="";
  $availLang=getAvailLang();
  if(is_array($availLang)){
    foreach($availLang as $l) {
      if($l==$language or (!isset($language) and $l==$cwLanguage)) $s="selected=\"selected\""; else $s="";
      $langSelect.="<option value=\"$l\" $s>$l</option>\n";
    }
  }
  //create the rule list
  $ruleSelect="";
  $ruleArr=$asterisk->getRule(0,RULE_OUTGOING);
  if(is_array($ruleArr)){
    foreach($ruleArr as $r) {
      if($r["id"]==$rule) $s="selected=\"selected\""; else $s="";
      $ruleSelect.="<option value=\"".$r["id"]."\" $s>".$r["name"]."</option>\n";
    }
  }
  //create extension list
  $all_linked_clients=array();
  $ret=$asterisk->getVirtualExtension(0);
  if(is_array($ret)){
  	foreach($ret as $vc){
    	if(is_array($vc["linked_clients"])){
      	$all_linked_clients=array_merge($all_linked_clients,$vc["linked_clients"]);
      }
    }
  }
  $listLeft="";
  $listRight="";
  $clientArr=$asterisk->getClient(0,0);
  if(is_array($clientArr)){
  	foreach($clientArr as $c){
    	if((is_array($linked_clients))&&(in_array($c["id"],$linked_clients,true))){
      	$listRight.="<option value=\"".$c["id"]."\">".$c["name"]." ".$c["surname"]." &lt;".$c["extension"]."&gt;</option>";
      }else{
      	if((!is_array($all_linked_clients))||(!in_array($c["id"],$all_linked_clients,true))){
      		$listLeft.="<option value=\"".$c["id"]."\">".$c["name"]." ".$c["surname"]." &lt;".$c["extension"]."&gt;</option>";
      	}
      }
    }
 	}
  //prepare the sidebar
  /*
  $retBuddy=$asterisk->getClient(0,0);
  if ($err=$asterisk->getError()) die("Error: $err");
  if (is_array($retBuddy))
  foreach ($retBuddy as $vBuddy) {
    $buddyid=$vBuddy["id"];
    $buddyExt=$vBuddy["extension"];
    $buddyName=$vBuddy["name"];
    $buddySurname=$vBuddy["surname"];
    $buddiesList.="<tr><td class=\"postit\"><a href=\"./?id=$buddyid\" >$buddyExt</a></td><td><a href=\"./?id=$buddyid\">$buddyName $buddySurname</a></td></tr>\n";
  }
  */
	
  //================ MAIN CONTENTS ================
  ob_start();
  $xajax->printJavascript("../../../../admin/lib/xajax/"); ?>
  <div class="SectionHeader">
    <div id="loading" style="float: right;"></div>
    <h1><?=$title?></h1>
    <h3><a href="../" class="admin" ><?=T_('Return without save')?></a></h3>
  </div>
  <div id="alert"></div>
  <div id="basic_form">
    <form id="mainform" action="<?=$PHP_SELF?>" method="post">
    <!-- Personal and Account Info -->
    <table>
      <tr>
        <td valign="top">
          <p class="blockintro"><?=T_('Personal information')?></p>
          <div class="block">
            <dl>
              <dt class="required"><label for="virtual[name]"><?=T_('Name')?>:</label></dt>
              <dd><input type="text" size="25" maxlength="30" id="virtual[name]" name="virtual[name]" value="<?=$name?>" /><span id="nameErr"></span></dd>
              <dt class="required"><label for="virtual[surname]"><?=T_('Surname')?>:</label></dt>
              <dd><input type="text" size="25" maxlength="50" id="virtual[surname]" name="virtual[surname]" value="<?=$surname?>" /><span id="surnameErr"></span></dd>
              <dt class="required"><label for="virtual[extension]"><?=T_('Extension')?>:</label></dt>
              <dd><input type="text" size="25" maxlength="20" id="virtual[extension]" name="virtual[extension]" value="<?=$extension?>" onkeyup="document.getElementById('virtual[username]').value=this.value;"  onblur="document.getElementById('virtual[username]').value=this.value;" /><span id="extensionErr"></span></dd>
	          <dt class="required"><label for="virtual[rule]"><?=T_('Rule set')?>:</label></dt>
              <dd><select id="virtual[rule]" name="virtual[rule]"><?=$ruleSelect?></select></dd>   
            </dl>
          </div>
        </td>
        <td valign="top">
          <p class="blockintro"><?=T_('Account Information')?></p>
          <div class="block">
            <dl>
              <dt class="required"><label for="virtual[username]"><?=T_('Username')?>:</label></dt>
              <dd><input type="text" size="25" maxlength="20" id="virtual[username]" name="virtual[username]" value="<?=$extension?>" disabled="disabled" /><span id="usernameErr"></span></dd>
              <dt class="required"><label for="virtual[password]"><?=T_('Password')?>:</label></dt>
              <dd><input type="password" size="25" maxlength="20" id="virtual[password]" name="virtual[password]" value="<?=$password?>" /><span id="passwordErr"></span></dd>
              <dt class="required"><label for="virtual[confirm]"><?=T_('Confirm')?>:</label></dt>
              <dd><input type="password" size="25" maxlength="20" id="virtual[confirm]" name="virtual[confirm]" value="<?=$password?>" /><span id="confirmErr"></span></dd>
              <dt class="required"><label for="virtual[language]"><?=T_('Language')?>:</label></dt>
              <dd><select id="virtual[language]" name="virtual[language]"><?=$langSelect?></select></dd>
            </dl>
          </div> 
        </td>
      </tr>
    </table>
    <!-- Linked Extension -->
    <h2><?=T_('Extensions')?></h2>
    <p class="blockintro"><?=T_('Select extensions to link to virtual extension')?></p>
    <div class="block">
    	<div>
        <table>
          <tr>
            <td class="required">
              <div><?=T_('Available extensions')?>:</div>
              <select multiple size="5"  name="listLeft[]" id="listLeft"><?=$listLeft?></select>
            </td>
            <td>   
              <div><input type="button" onclick="moveTrunkList( document.getElementById('listLeft'),  document.getElementById('listRight'), false , true)" name="Add     >>"  value="<?=T_('Add')?>     >" style="width:100px"></div>
              <div><input type="button" onclick="moveTrunkList( document.getElementById('listRight'), document.getElementById('listLeft'),  false )" name="Add     <<"  value="<    <?=T_('Remove')?>" style="width:100px"></div>
              <!--<div><input type="button" onclick="moveTrunkList( document.getElementById('listLeft'),  document.getElementById('listRight'), true  , true)" name="Add All >>"  value="<?=$cwlang["ruleout"]["addAll"]?>" style="width:100px"></div>-->
              <!--<div><input type="button" onclick="moveTrunkList( document.getElementById('listRight'), document.getElementById('listLeft'),  true  )" name="Add All <<"  value="<?=$cwlang["ruleout"]["removeAll"]?>" style="width:100px"></div>-->
            </td>
            <td class="required"><div><?=T_('Selected extensions')?>:&nbsp;&nbsp;<span id="linked_clientsErr"></span></div>
              <div style="float: left">
                <!--<input type="image"  src="<?=$relBasePath?>public/img/icon_up.gif"  onclick="moveOptions ( document.getElementById('listRight'), -1); return false" name="Up"  value="Down" style="display: block">-->
                <!--<input type="image"  src="<?=$relBasePath?>public/img/icon_down.gif"  onclick="moveOptions ( document.getElementById('listRight'), 1); return false;" name="Down"  value="Down" style="display: block">-->
              </div>
                <select multiple size="5" name="listRight[]" id="listRight"><?=$listRight?></select>
            </td>
          </tr>
        </table>
      </div>
      <br/>
    </div>
    <!-- Voice Mail -->
    <h2><?=T_('VoiceMail')?></h2>
    <p class="blockintro"><?=T_('Insert here the voicemail information')?></p>
    <div class="block">
      <dl>
        <dt class="required"><label for="virtual[voicemailOn]"><?=T_('Active')?>:</label></dt>
        <dd>
          <input type="hidden" id="virtual[vid]" name="virtual[vid]" value="<?=$vid?>" />
          <input type="radio" id="virtual[voicemailOn]" name="virtual[voicemailOn]" value="1" <?if ($voicemailOn==1) echo "checked=\"checked\""; ?> /> <?=T_('ON')?>
          <input type="radio" id="virtual[voicemailOn]" name="virtual[voicemailOn]" value="0" <?if ($voicemailOn!=1) echo "checked=\"checked\""; ?> /> <?=T_('OFF')?>
        </dd>
        <dt class="required"><label for="virtual[email]"><?=T_('Email')?>:</label></dt>
        <dd><input type="text" size="25" maxlength="100" id="virtual[email]" name="virtual[email]" value="<?=$email?>" /> <?=T_('Email address (leave blank for no notification)')?></dd>
        <dt class="required"><label for="virtual[vpassword]"><?=T_('Password')?>:</label></dt>
        <dd><input type="password" size="25" maxlength="20" id="virtual[vpassword]" name="virtual[vpassword]" value="<?=$vpassword?>" /><span id="vpasswordErr"></span> <?=T_('Set the password to hear voicemail')?></dd>
        <dt class="required"><label for="virtual[vconfirm]"><?=T_('Confirm')?>:</label></dt>
        <dd><input type="password" size="25" maxlength="20" id="virtual[vconfirm]" name="virtual[vconfirm]" value="<?=$vpassword?>" /><span id="vconfirmErr"></span> <?=T_('Confirm the password to hear voicemail')?></dd>
        <dt class="required"><label for="virtual[attach]"><?=T_('Attach')?>:</label></dt>
        <dd><input type="checkbox" id="virtual[attach]" name="virtual[attach]" value="1" <?if ($attach==1) echo "checked=\"checked\""; ?> />
        <?=T_('If enabled, the audio message will be sent as attachment to your email')?> </dd>
        <dt class="required"><label for="virtual[saycid]"><?=T_('Say CID')?>:</label></dt>
        <dd><input type="checkbox" id="virtual[saycid]" name="virtual[saycid]" value="1" <?if ($saycid==1) echo "checked=\"checked\""; ?> />
        <?=T_('If enabled, the Caller ID will be included')?></dd>
        <dt class="required"><label for="virtual[hidefromdir]"><?=T_('Hide')?>:</label></dt>
        <dd><input type="checkbox" id="virtual[hidefromdir]" name="virtual[hidefromdir]" value="1"  <?if ($hidefromdir==1) echo "checked=\"checked\""; ?> />
        <?=T_('If enabled, you will be hidden from the directory')?></dd>
      </dl>
    </div>
    <!-- Caller ID -->
    <h2><?=T_('Caller ID')?></h2>
    <p class="blockintro"><?=T_('Set CID on outgoing lines')?></p>
    <div class="block">
      <dl>
        <dt class="required"><label for="trunklist"><?=T_('Line')?>:</label></dt>
        <dd><select id="trunklist" name="trunklist"><?=$trunklist?></select><span> <img src="<?=$relBasePath?>/public/img/add.gif" alt="addCid" onclick=" addCidRow(); "/>&nbsp;<?=T_('add personal Caller ID for selected line')?></span></dd>
      </dl>
      <table id="stats" cellpadding="0" cellspacing="0">
        <tr><th></th><th><?=T_('CLIR')?></th><th><?=T_('Line')?></th><th><?=T_('CID Number')?></th><th><?=T_('CID Name')?></th><th><?=T_('Line Overwrite')?></th></tr>
        <span id="intable"><?=$cidlist?></span>
      </table>
    </div>   
    <!-- Groups -->
    <? echo listGroup(GROUP_OF_EXTENSION, $js, $groupsArr); ?>              
 		<!-- Buttons -->
    <div class="action">
      <?if ($_GET["id"]!="") {?> <input type="hidden" id="virtual[id]" name="virtual[id]" value="<?=$id?>" /><?}?>
      <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/></a>
      <a href="#"><img src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick=" selectAll(getElementById('listRight')); document.getElementById('alert').innerHTML=''; xajax_processFormData(xajax.getFormValues('mainform')); "/></a>
   <!--  
      <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-cancel.gif" alt="Cancel" onclick="location.href='../'; return false;"/>             
      <input type="image" src="<?=$relBasePath?>/public/img/<?=$cwLanguage?>/b-save.gif" alt="Save" onclick="return checkParam(document.getElementById('client[extension]').value, document.getElementById('client[alias]').value, document.getElementById('client[password]').value, document.getElementById('client[confirm]').value);"/>
    -->
    </div>
  </form>
 </div>   
 
  <script>
    function addCidRow(){
      document.getElementById('alert').innerHTML=''; 
      var newRowIndex = (document.getElementById('stats').rows.length);
      var newRow = document.getElementById('stats').insertRow(newRowIndex);
      newRow.id = document.getElementById('trunklist').options[document.getElementById('trunklist').selectedIndex].value + "_row";
      newRow.bgColor = "#ffffff";
      var newCell_0 = newRow.insertCell(0); newCell_0.id = newRow.id + "_cell0";
      var newCell_1 = newRow.insertCell(1); newCell_1.id = newRow.id + "_cell1";
      var newCell_2 = newRow.insertCell(2); newCell_2.id = newRow.id + "_cell2";
      var newCell_3 = newRow.insertCell(3); newCell_3.id = newRow.id + "_cell3";
      var newCell_4 = newRow.insertCell(4); newCell_4.id = newRow.id + "_cell4";
      var newCell_5 = newRow.insertCell(5); newCell_5.id = newRow.id + "_cell5";
      xajax_addCid(document.getElementById('trunklist').options[document.getElementById('trunklist').selectedIndex].value);
    } 
  </script>
  
  <?
  $contents=ob_get_contents();
  ob_end_clean();
  //================ SIDEBAR ================
  ob_start(); 
  ?>
    <div class="Sidebar">
      <?$sel="extensions";include("../../sidebar.php");?>
      <h1><?=T_('Informations')?></h1>
    </div>
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();
  //================ SETTINGS ================
  sajax_handle_client_request();
  $smarty->assign("section", "extensions");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->assign("ajax", $js);
  $smarty->display('settings.tpl');
?>

